package com.spring.shops.admin.controller.login;

import com.spring.shops.constant.JwtClaimsConstant;
import com.spring.shops.dao.TzSysUserMapper;
import com.spring.shops.model.dto.CaptchaAuthenticationDTO;
import com.spring.shops.model.entity.TzSysUser;
import com.spring.shops.model.result.ServerResponseEntityVoid;
import com.spring.shops.model.vo.LoginVO;
import com.spring.shops.properties.JwtProperties;
import com.spring.shops.service.AdminService;
import com.spring.shops.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private TzSysUserMapper mapper;
    /**
     * 用户登录+校验码(密码前端加密过）
     * @param authenticationDTO
     */
    @PostMapping("/adminLogin")
    public ServerResponseEntityVoid login(@RequestBody CaptchaAuthenticationDTO authenticationDTO){
        ServerResponseEntityVoid login = adminService.login(authenticationDTO);
        if(login.isSuccess()){
            //成功的话
            TzSysUser user = (TzSysUser)login.getData();
            //登录成功后，生成jwt令牌
            Map<String, Object> claims = new HashMap<>();
            claims.put(JwtClaimsConstant.user_ID, user.getUserId());
            String token = JwtUtil.createJWT(
                    jwtProperties.getAdminSecretKey(),
                    jwtProperties.getAdminTtl(),
                    claims);
            //创建登录成功返回的实体
            LoginVO loginVO = new LoginVO(token, token, jwtProperties.getAdminTtl());
            return ServerResponseEntityVoid.LoginSuccess(loginVO);
        }else{
            return login;
        }

    }
    /**
     * 用户退出登录
     */
    @PostMapping("/logOut")
    public ServerResponseEntityVoid logout(){
        //用户退出登录需要删除token,直接返回即可，前端自动会删除token
        return ServerResponseEntityVoid.success();
    }

    /**
     * 添加用户
     * @param tzSysUser
     * @return
     */
    @PostMapping ("/add")
    public String add(@RequestBody TzSysUser tzSysUser){
       return adminService.add(tzSysUser);
    }

}
